package org.jash.ting13.book

import android.content.ComponentName
import android.net.Uri
import android.widget.Toast
import androidx.annotation.OptIn
import androidx.lifecycle.lifecycleScope
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.datasource.ResolvingDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.session.MediaController
import androidx.media3.session.MediaSession
import androidx.media3.session.SessionToken
import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver
import com.google.common.util.concurrent.ListenableFuture
import com.google.common.util.concurrent.MoreExecutors
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import kotlinx.coroutines.launch
import org.jash.ting13.databinding.ActivityBookBinding
import org.jash.ting13.entity.Chapter
import org.jash.ting13.entity.PlayUrl
import org.jash.ting13.net.APIService
import org.jash.ting13.service.AudioService
import org.jash.ting13.service.mediaSourceFactory
import org.jash.utils.Event
import org.jash.utils.log
import org.jash.utils.mvi.BaseActivity
import org.jash.utils.net.service

class BookActivity : BaseActivity<ActivityBookBinding, BookViewModel>() {
    lateinit var url:String
    lateinit var adapter: ChapterAdapter
    lateinit var controllerFuture:ListenableFuture<MediaController>
    override fun initData() {
        url = intent.getStringExtra("url") ?: ""
        adapter = ChapterAdapter()
        adapter.registerAdapterDataObserver(object : AdapterDataObserver() {
            override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                for (i in 0..< itemCount) {
//                    val item =
//                        MediaItem.fromUri(adapter.getChapter(positionStart + i)?.url ?: "")
                    val chapter = adapter.getChapter(positionStart + i)
                    val item =
                        MediaItem.Builder()
                            .setMediaId(chapter?.url ?: "")
                            .setUri(chapter?.url)
                            .setMediaMetadata(
                                MediaMetadata.Builder()
                                    .setTitle(chapter?.title)
                                    .setAlbumTitle(binding.book?.title)
                                    .build()
                            )
                            .build()
                    controllerFuture.get().addMediaItem(positionStart + i, item)
                }
            }
        })
         viewModel.state.observe(this) {
            when(it) {
                is BookState.Success -> binding.book = it.book
                is BookState.Paging -> {
                    lifecycleScope.launch {
                        adapter.submitData(it.data)
                    }
                }
                is BookState.Failure -> Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()

            }
        }
        viewModel.intent.trySend(BookIntent.LoadDetail(url))
    }

    @OptIn(UnstableApi::class)
    override fun onStart() {
        super.onStart()
        val sessionToken = SessionToken(this, ComponentName(this, AudioService::class.java))
        controllerFuture = MediaController.Builder(this, sessionToken).buildAsync()
        controllerFuture.addListener({
            binding.playControl.player = controllerFuture.get()
        }, MoreExecutors.directExecutor())

    }
    @OptIn(UnstableApi::class)
    override fun initView() {
        binding.recycler.adapter = adapter
        binding.toolbar.setNavigationOnClickListener { finish() }
    }
    @Event("loadPlay")
    fun loadPlay(chapter: Chapter) {
        for (i in 0..<adapter.itemCount) {
            if (adapter.getChapter(i) == chapter){
                controllerFuture.get().seekTo(i, C.INDEX_UNSET.toLong())
                controllerFuture.get().prepare()
                controllerFuture.get().play()
                break
            }
        }

    }

    override fun onStop() {
        super.onStop()
        MediaController.releaseFuture(controllerFuture)
    }

}
